<?php

class InstallForm extends CFormModel
{
	public $appName;
	public $dbHost;
	public $dbName;
	public $dbUsername;
	public $dbPassword;
	public $dbTablePrefix;
	public $adminUsername;
	public $adminPassword;
	public $adminEmail;

	/**
	 * @var CDbConnection
	 */
	private $_connection;

	public function rules()
	{
		return array(
			array('appName, dbHost, dbName, dbUsername, adminUsername, adminPassword, adminEmail', 'required'),
			array('appName', 'match', 'pattern' => '|^[0-9a-z\-]+$|i', 'message' => '{attribute} 只能包含英文和 数字 、-.'),
			array('adminEmail', 'email'),
			array('dbPassword, dbTablePrefix', 'length'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'appName' => '应用名称',
			'dbHost' => '数据库地址',
			'dbName' => '数据库名',
			'dbUsername' => '数据库用户',
			'dbPassword' => '数据库密码',
			'dbTablePrefix' => '数据库表前缀',
			'adminUsername' => '管理员用户名',
			'adminPassword' => '管理员用户密码',
			'adminEmail' => '管理员电子邮箱',
		);
	}

	public function install()
	{
		if (!$this->validate()) {
			return false;
		}
		if (!$this->installSchema()) {
			return false;
		}

		$this->_connection->tablePrefix = $this->dbTablePrefix;
		Yii::app()->setComponent('db', $this->_connection);
		$user = new User();
		$user->id = 1;
		$user->username = $this->adminUsername;
		$user->email = $this->adminEmail;
		$user->setPassword($this->adminPassword);
		$user->save(false);

		$this->writeConfigFile();
		return true;
	}

	protected  function installSchema()
	{
		$schemaFile = Yii::getPathOfAlias('install.data.schema') . '.php';
		if (!file_exists($schemaFile)) {
			throw new CException('安装SQL文件未找到');
		}
		$sql = require $schemaFile;
		$sql = strtr($sql, array(
			'{tablePrefix}' => $this->dbTablePrefix,
		));
		$transaction = $this->_connection->beginTransaction();
		try {
			$this->_connection->createCommand($sql)->execute();
			$transaction->commit();
		} catch (CDbException $e) {
			$transaction->rollback();
			return false;
		}
		return true;
	}

	protected function writeConfigFile()
	{
$dbConfig = <<<EOT
<?php
define('DB_HOST', '{$this->dbHost}');
define('DB_NAME', '{$this->dbName}');
define('DB_USERNAME', '{$this->dbUsername}');
define('DB_PASSWORD', '{$this->dbPassword}');
define('DB_TABLE_PREFIX', '{$this->dbTablePrefix}');
EOT;
$commonConfig = <<<EOT
<?php
define('INSTALLED', true);

require dirname(__FILE__) . '/db.php';

return array(
	'name' => '{$this->appName}',
	'components' => array(
		'db' => array(
			'connectionString' => 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME,
			'username' => DB_USERNAME,
			'password' => DB_PASSWORD,
			'tablePrefix' => DB_TABLE_PREFIX,
		),
	),
);
EOT;
$mainConfig = <<<EOT
<?php
return array(
	'basePath' => dirname(__FILE__) . '/../',
);
EOT;
		$backendConfig = '<?php return array();';
		$configDir = Yii::getPathOfAlias('frontend.config');
		if (!is_dir($configDir)) {
			@mkdir($configDir);
		}
		file_put_contents($configDir . '/common.php', $commonConfig);
		file_put_contents($configDir . '/db.php', $dbConfig);
		file_put_contents($configDir . '/backend.php', $backendConfig);
		file_put_contents($configDir . '/main.php', $mainConfig);
	}

	protected function afterValidate()
	{
		parent::afterValidate();
		$this->_connection = new CDbConnection("mysql:host={$this->dbHost};dbname={$this->dbName}", $this->dbUsername, $this->dbPassword);
		$this->_connection->charset = 'utf8';
		try {
			$this->_connection->init();
		} catch (CDbException $e) {
			$this->addError('dbHost', '数据库连接失败，请检查数据库用户名和密码');
		}
	}
}
